import { TagList } from '@entities/Tags'
import { ResponseTask, TaskCard, TaskCardsList, TaskType } from '@entities/Tasks'
import { EditTaskForm, useTags } from '@features/EditTaskForm'
import { TaskDeleteButton, TaskDoneButton } from '@features/TaskCardActions'
import { TasksFilterTabs } from '@features/TasksFilterTabs'
import { useGetTasksQuery } from '@shared/api'
import { useAppDispatch, useAppSelector } from '@shared/lib/hooks/redux'
import { UiActions } from '@shared/lib/store/UiSlice'
import { Button } from '@shared/ui/Button'
import { useEffect, useState } from 'react'
import styles from './TaskPageContent.module.scss'

export const TasksPageContent = () => {
  const { data: tasks, isLoading: tasksLoading } = useGetTasksQuery()
  const dispatch = useAppDispatch()
  const { currentFilter } = useAppSelector((state) => state.tasks)
  const [searchedTask, setSearchedTask] = useState<ResponseTask[]>([])
  const [view, setView] = useState<'format_list_bulleted' | 'grid_view'>('grid_view')
  const { getTags } = useTags()

  useEffect(() => {
    tasks && setSearchedTask(tasks)
  }, [tasks])

  const editTask = (task: ResponseTask) => {
    dispatch(UiActions.openPopup(<EditTaskForm task={task} />))
  }

  const addTask = () => {
    dispatch(UiActions.openPopup(<EditTaskForm />))
  }

  const filteredTasks =
    currentFilter === TaskType.ALL
      ? searchedTask
      : searchedTask?.filter((task) => task.type === currentFilter)

  const changeView = () => {
    setView((prev) => (prev === 'grid_view' ? 'format_list_bulleted' : 'grid_view'))
  }
  const renderIcons = () => <Button iconName={`${view}`} onClick={changeView} size='extra-small' />
  return (
    <>
      <TasksFilterTabs renderAction={renderIcons} />
      <div className={styles['list-wrapper']}>
        <TaskCardsList
          addTask={addTask}
          isLoading={tasksLoading}
          renderTask={(task: ResponseTask) => (
            <TaskCard
              key={task.id}
              onClick={editTask}
              renderActions={{
                renderDeleteBtn: (task) => <TaskDeleteButton task={task} />,
                renderDoneBtn: (task) => <TaskDoneButton task={task} />,
              }}
              renderTags={(task) => <TagList tagList={getTags(task?.tagsIds)} />}
              task={task}
              view={view}
            />
          )}
          tasks={filteredTasks}
          view={view}
        />
      </div>
    </>
  )
}
